package com.jml.netty.手写注册中心;

import com.jml.netty.手写注册中心.entity.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


public class RegistryServer {

    public void bind(int port) throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1280)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 新增Marshaling编码器
                            ch.pipeline().addLast(
                                    MarshallingCodeCFactory.buildMarshallingDecoder()
                            );
                            ch.pipeline().addLast(
                                    MarshallingCodeCFactory.buildMarshallingEncoder()
                            );
                            ch.pipeline().addLast(
                                    new ServerHandler()
                            );
                        }
                    });

            ChannelFuture f = b.bind(port).sync();

            f.channel().closeFuture().sync();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8006;
        new RegistryServer().bind(port);
    }

    public static final int type_producer = 0;
    public static final int type_consumer = 1;

    // key 服务的名称 value 多个生产者集群地址列表
    private static ConcurrentHashMap<String, List<AddresEntity>> keyAddres = new ConcurrentHashMap<>();
    //key 为连接 value 服务名称
    private static ConcurrentHashMap<ChannelHandlerContext, String> ctxs = new ConcurrentHashMap<>();

    @ChannelHandler.Sharable
    public class ServerHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            AgreementEntity agreement = (AgreementEntity) msg;
            // 1.判断通讯协议类型： 生产还是消费者
            switch (agreement.getType()) {
                case type_producer:
                    producer(agreement, ctx);
                    ctxs.put(ctx, agreement.getServiceId());
                    break;
                case type_consumer:
                    consumer(agreement, ctx);
                    // 应该存放消费者连接
                    break;

            }
        }

        /**
         * 生产者
         *
         * @param agreement
         * @param ctx
         */
        private void producer(AgreementEntity agreement, ChannelHandlerContext ctx) {
            String serviceId = agreement.getServiceId();
            // 根据服务名称查找之前是否有缓存地址数据
            List<AddresEntity> listAddres = keyAddres.get(serviceId);
            if (listAddres == null) {
                listAddres = new ArrayList<>();
                keyAddres.put(serviceId, listAddres);
            }
            // 注册中心插入服务地址信息
            String addres = agreement.getAddres();
            listAddres.add(new AddresEntity(addres, ctx));
        }

        /**
         * 消费者
         */
        private void consumer(AgreementEntity agreement, ChannelHandlerContext ctx) {
            String serviceId = agreement.getServiceId();
            List<AddresEntity> addresEntities = keyAddres.get(serviceId);
            if (addresEntities == null || addresEntities.size() == 0) {
                ctx.writeAndFlush(new RespEntity(500, "未获取接口地址列表"));
                return;
            }
            // 数据格式转换
            ArrayList<AddresDto> addresDtos = new ArrayList<>();
            addresEntities.forEach((t) -> {
                addresDtos.add(new AddresDto(t.getAddres()));
            });
            ctx.writeAndFlush(new RespEntity(200, "接口地址列表", addresDtos));
        }


        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            // 如果客户端主动断开连接的时候 走该方法 那个连接主动断开
            //// key 服务的名称 value 多个生产者集群地址列表

            // 服务名称 缓存3个  每个服务名称对应缓存三个集群地址列表
            //  private static ConcurrentHashMap<String, List<AddresEntity>> keyAddres = new ConcurrentHashMap<>();
            // 多个服务名称 对应对个 服务地址集群理列表

            //ChannelHandlerContext ctx==对应地址
            String serviceId = ctxs.get(ctx);
            // 根据服务名称查找缓存地址
            List<AddresEntity> addresEntities = keyAddres.get(serviceId);
            // 遍历缓存地址剔除
            addresEntities.forEach((t) -> {
                if (t.getCtx() == ctx) {
                    //剔除
                    addresEntities.remove(t);
                }
            });
            // 注册中心通知消费者删除失效地址
            // 循环遍历所有的消费者连接，通知  服务名称 那个地址 应该从内存删除
            ctx.close();
        }
    }


}
